/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package converter.controller;

import converter.model.Currency;
import converter.model.CurrencyDTO;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Iterator;
/**
 *
 * @author reverende
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Stateless
public class ConverterFacade {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    
    @PersistenceContext(unitName = "currencyConverterPU")
    private EntityManager em;
    
    public CurrencyDTO createCurrency(String currencyName, double exchangeRate) {
        Currency newCurrency = new Currency(currencyName, exchangeRate);
        em.persist(newCurrency);
        return newCurrency;
    }
	
    public Currency findCurrency(String currencyName) {
        
      List<Currency> c = getCurrencies();
      Iterator<Currency> i = c.iterator();
      Currency currency = null,tmp;
      while(i.hasNext())
      {
          tmp = i.next();
          if (tmp.getName().equals(currencyName))
          {
              currency = tmp;
              break;
          }
      }
      if (currency == null)
          System.out.println("Couldn't find currency");
      return currency;
    }
    
    public List<Currency> getCurrencies()
    {
        List<Currency> currencies = em.createQuery("select c from Currency c").getResultList();
        return currencies;
        
    }

}


